package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.mall.common.exception.BadRequestException;
import com.mall.common.utils.BeanUtils;
import com.mall.common.utils.UserContext;
import com.mall.domain.dto.ItemDTO;
import com.mall.domain.dto.OrderDetailDTO;
import com.mall.domain.dto.OrderFormDTO;
import com.mall.domain.po.Order;
import com.mall.domain.po.OrderDetail;
import com.mall.domain.response.Response;
import com.mall.domain.vo.OrderCountVO;
import com.mall.domain.vo.OrderVO;
import com.mall.enums.OrderStatus;
import com.mall.mapper.OrderMapper;
import com.mall.service.CartService;
import com.mall.service.IOrderDetailService;
import com.mall.service.IOrderService;
import com.mall.service.ItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.domain.PageDTO;
import com.mall.common.domain.PageQuery;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final ItemService itemService;
    private final IOrderDetailService detailService;
    private final CartService cartService;
    private final OrderMapper orderMapper ;

    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();
        // 1.3.查询商品
        List<ItemDTO> items = itemService.getItemByIds(itemIds);
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("商品不存在");
        }
        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int total = 0;
        for (ItemDTO item : items) {
            total += item.getPrice() * itemNumMap.get(item.getId());
        }
        order.setTotalFee(total);
        // 1.5.其它属性
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(UserContext.getUser());
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetails(order.getId(), items, itemNumMap);
        detailService.saveBatch(details);

        // 3.清理购物车商品
        cartService.removeByItemIds(itemIds);

        // 4.扣减库存
        try {
            itemService.deDuckStock(detailDTOS);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
        return order.getId();
    }

    @Override
    public void markOrderPaySuccess(Long orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(2);
        order.setPayTime(LocalDateTime.now());
        updateById(order);
    }

    @Override
    public Response<OrderCountVO> dashboard() {
        OrderCountVO orderCountVO = new OrderCountVO();
        // 今日
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        // 构建查询条件
        QueryWrapper<Order> queryWrapper1 = new QueryWrapper<>();
        QueryWrapper<Order> queryWrapper2 = new QueryWrapper<>();
        queryWrapper1.between("create_time", startOfDay, endOfDay);
        queryWrapper2.eq("status",2);

        // 执行查询
        int todayOrderCount = Math.toIntExact(orderMapper.selectCount(queryWrapper1));
        long todaySalesAmount = 0;
        for (Order order : this.list(queryWrapper1)) {
            todaySalesAmount+=order.getTotalFee();
        }
        Long PendingShipCount = orderMapper.selectCount(queryWrapper2);

        // 设置今日订单数量
        orderCountVO.setTodayOrderCount(todayOrderCount);
        orderCountVO.setTodaySalesAmount(todaySalesAmount);
        // 待发货订单数
        orderCountVO.setPendingShipCount(PendingShipCount);

        return Response.success(orderCountVO);
    }

    @Override
    public Response<PageDTO<OrderVO>> getOrderList(PageQuery pageQuery, String orderNo, Integer status, String startDate, String endDate) {
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = Wrappers.lambdaQuery(Order.class);
        
        // 按订单号查询
        if (StringUtils.isNotBlank(orderNo)) {
            queryWrapper.like(Order::getId, orderNo);
        }
        
        // 按状态查询
        if (status != null && status > 0) {
            queryWrapper.eq(Order::getStatus, status);
        }
        
        // 按日期范围查询
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (StringUtils.isNotBlank(startDate)) {
            LocalDate start = LocalDate.parse(startDate, formatter);
            queryWrapper.ge(Order::getCreateTime, start.atStartOfDay());
        }
        if (StringUtils.isNotBlank(endDate)) {
            LocalDate end = LocalDate.parse(endDate, formatter);
            queryWrapper.le(Order::getCreateTime, end.atTime(23, 59, 59));
        }
        
        // 按创建时间降序排列
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        // 执行分页查询
        Page<Order> page = pageQuery.toMpPageDefaultSortByCreateTimeDesc();
        page = this.page(page, queryWrapper);
        
        // 转换为VO对象
        PageDTO<OrderVO> pageDTO = PageDTO.of(page, OrderVO.class);
        
        return Response.success(pageDTO);
    }

    private List<OrderDetail> buildDetails(Long orderId, List<ItemDTO> items, Map<Long, Integer> numMap) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(numMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(orderId);
            details.add(detail);
        }
        return details;
    }
    
    @Override
    @Transactional
    public boolean cancelOrder(Long orderId) {
        // 查询订单
        Order order = getById(orderId);
        if (order == null) {
            throw new BadRequestException("订单不存在");
        }
        
        // 检查订单状态，只有未付款(1)或已付款未发货(2)的订单才能取消
        if (order.getStatus() != 1 && order.getStatus() != 2) {
            throw new BadRequestException("当前订单状态无法取消");
        }
        
        // 更新订单状态为已取消(5)
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(5); // 订单关闭状态
        updateOrder.setCloseTime(LocalDateTime.now()); // 设置关闭时间
        
        return updateById(updateOrder);
    }
    
    @Override
    @Transactional
    public boolean shipOrder(Long orderId, String expressCompany, String trackingNumber) {
        // 查询订单
        Order order = getById(orderId);
        if (order == null) {
            throw new BadRequestException("订单不存在");
        }
        
        // 检查订单状态，只有已付款未发货(2)的订单才能发货
        if (order.getStatus() != 2) {
            throw new BadRequestException("当前订单状态无法发货");
        }
        
        // 更新订单状态为已发货(3)
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(3); // 已发货状态
        updateOrder.setConsignTime(LocalDateTime.now()); // 设置发货时间
        
        // 更新物流信息（如果存在物流服务）
        // 这里可以根据实际需求调用物流服务更新物流信息
        
        return updateById(updateOrder);
    }

    @Override
    public Response<List<OrderVO>> myOrders(Integer status) {
        Long userId = UserContext.getUser();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            if (status==null){
                wrapper.eq(Order::getUserId, userId).orderByDesc(Order::getCreateTime);
            }
            else
            {
                wrapper.eq(Order::getUserId, userId).orderByDesc(Order::getCreateTime).eq(Order::getStatus,status);
            }

            List<Order> list = this.list(wrapper);
            List<OrderVO> orderVOS = list.stream()
                    .map(order -> {
                        OrderVO orderVO = new OrderVO();
                        BeanUtils.copyProperties(order, orderVO);
                        return orderVO;
                    }).toList();

            return Response.success(orderVOS);



    }

    @Override
    public Response<?> shipping(Long orderid) {
        Order byId = getById(orderid);
        byId.setStatus(OrderStatus.SHIPPING_NOT_CONFIRMED.getStatus());
        updateById(byId);
        return Response.success();
    }
}
